/*
 * @Description: 档案备份计划 页面标题组件
 * @Author: Rfan
 * @Date: 2022-08-03 20:29:15
 * @LastEditTime: 2023-03-01 20:29:54
 */

import { useEffect, useState } from 'react';
import { Button, Col, DatePicker, Form, Input, Radio, Row, Select, Space } from 'antd';
import dayjs from 'dayjs';
import classNames from 'classnames/bind';
import { observer } from 'mobx-react-lite';
import { appState } from '@/store/mobx';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { fetchATListByFondId, fetchLevelByATId, fetchRepoListByType } from '@/api/archivesType';
import { DefaultOptionType } from 'rc-select/lib/Select';
import type { IFond } from '@/interfaces/fond';
import type { IArchiveType, ILevel, IRepo } from '@/interfaces/archiveType';
import styles from '../styles/tableFilter.module.scss';

const cx = classNames.bind(styles);

const { RangePicker } = DatePicker;

const PageTitle = () => {
  const [form] = Form.useForm();

  // 全宗列表
  const [fondList, setFondList] = useState<DefaultOptionType[]>([]);
  // 档案类型列表
  const [atTypeList, setAtTypeList] = useState<IArchiveType[]>([]);
  // 档案类型列表
  const [atTypeOptions, setAtTypeOptions] = useState<DefaultOptionType[]>([]);
  // 层级列表
  const [levelList, setLevelList] = useState<DefaultOptionType[]>([]);
  // 库列表
  const [repoList, setRepoList] = useState<DefaultOptionType[]>([]);

  useEffect(() => {
    if (appState.unitId) {
      fetchFondsListByUnitId(appState.unitId).then((res) => {
        const _list: IFond[] = res.data || [];
        setFondList(_list.map((fond) => ({ label: fond.fondName, value: fond.id })));
      });
    }
  }, [appState.unitId]);

  /**
   * @description: 选择全宗变化事件
   * @param {string} value 选中的全宗ID
   */
  const onFondChange = (value: string) => {
    console.log(value);
    if (value) {
      fetchATListByFondId(value).then((res) => {
        const _list: IArchiveType[] = res.data || [];
        setAtTypeList(_list);
        setAtTypeOptions(_list.map((item) => ({ label: item.atName, value: item.id })));
      });
    } else {
      form.setFieldsValue({ archiveTypeId: '', level: '', dbName: '' });
      setAtTypeList([]);
      setAtTypeOptions([]);
      setLevelList([]);
      setRepoList([]);
    }
  };

  /**
   * @description: 选择档案类型变化事件
   * @param {string} value 选中的档案类型ID
   */
  const onATChange = (value: string) => {
    if (value) {
      const selectAt = atTypeList.find((item) => item.id === parseInt(value, 10));
      const levelPromise = fetchLevelByATId(value);
      const repoPromise = fetchRepoListByType(selectAt.atType, value);
      Promise.all([levelPromise, repoPromise]).then(([levelRes, repoRes]) => {
        const _levelList: ILevel[] = levelRes.data || [];
        const _repoList: IRepo[] = repoRes.data || [];
        setLevelList(_levelList.map((item) => ({ label: item.levelName, value: item.level })));
        setRepoList(_repoList.map((item) => ({ label: item.description, value: item.name })));
      });
    } else {
      form.setFieldsValue({ level: '', dbName: '' });
      setLevelList([]);
      setRepoList([]);
    }
  };

  const onReset = () => {
    form.resetFields();
  };

  const onSubmit = () => {
    form.submit();
  };

  const onFinish = (values: any) => {
    console.log('retrieval:', values);
    // getRecycleBinList();
  };

  return (
    <div className={cx('table-filter')}>
      <Row className={cx('filter-title')} justify="space-between">
        <Col>
          <h4 className={cx('page-title')}>档案篮信息筛选</h4>
        </Col>
        <Col>
          <Space size="small">
            <Button
              onClick={() => {
                onSubmit();
              }}
            >
              查询
            </Button>
            <Button
              onClick={() => {
                onReset();
              }}
            >
              重置
            </Button>
          </Space>
        </Col>
      </Row>
      <div className={cx('filter-form')}>
        <Form layout="inline" preserve={false} form={form} onFinish={onFinish}>
          <Form.Item label="时间">
            <Radio.Group disabled>
              <Radio value="1">全部</Radio>
              <Radio value="2">自定义</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <RangePicker
              disabled
              ranges={
                {
                  Today: [dayjs(), dayjs()],
                  'This Month': [dayjs().startOf('month'), dayjs().endOf('month')]
                } as any
              }
            />
          </Form.Item>
          <Form.Item label="全宗" name="fondsId">
            <Select options={fondList} allowClear style={{ width: 200 }} onChange={onFondChange} />
          </Form.Item>
          <Form.Item label="档案类型" name="archiveTypeId">
            <Select
              options={atTypeOptions}
              allowClear
              style={{ width: 180 }}
              onChange={onATChange}
            />
          </Form.Item>
          <Form.Item label="所属层级" name="level">
            <Select options={levelList} allowClear style={{ width: 140 }} />
          </Form.Item>
          <Form.Item label="来源库" name="dbName">
            <Select options={repoList} allowClear style={{ width: 120 }} />
          </Form.Item>
          <Form.Item label="题名" name="title">
            <Input allowClear />
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default observer(PageTitle);
